<template>
  <div>
    <div class="filter-container">
      <el-input v-model="listQuery.caseName" placeholder="请输入用例编号或名称" size="medium" style="width: 200px;" class="filter-item" @keyup.native="handleFilter" />
      <el-select v-model="listQuery.caseType" placeholder="用例类型" clearable size="medium" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in caseType" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button :disabled="!addFlag" class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="createHandle">
        新增测试用例
      </el-button>
      <el-dropdown @command="batchHandle">
        <el-button type="danger" size="medium">
          批量操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="addSuite">添加到测试集</el-dropdown-item>
          <el-dropdown-item command="changeFolder">变更目录</el-dropdown-item>
          <el-dropdown-item command="batchDel">批量删除</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshTable">
        刷新
      </el-button>
    </div>
    <el-table
      ref="dataTable"
      v-loading="listLoading"
      border
      highlight-current-row
      :data="pageData"
      style="width: 100%"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="case_num"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="用例编号"
        min-width="140"
      />
      <el-table-column
        prop="case_title"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        min-width="140"
        label="用例名称"
      />
      <el-table-column
        prop="step_count"
        sortable
        align="center"
        min-width="80"
        label="用例步骤"
      >
        <template slot-scope="scope">
          <router-link :to="'/caseCategory/step/' + scope.row.id + '/' + scope.row.case_title">
            <el-tag class="step-count" :type="scope.row.step_count === 0 ? 'info': ''">{{ scope.row.step_count }}</el-tag>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="case_type"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        min-width="100"
        label="用例类型"
      />
      <el-table-column
        prop="create_time"
        sortable
        align="center"
        min-width="140"
        :show-overflow-tooltip="true"
        label="创建时间"
      />
      <el-table-column
        prop="creator_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="创建人"
      />
      <el-table-column
        prop="mark"
        :show-overflow-tooltip="true"
        sortable
        align="center"
        min-width="80"
        label="备注"
      />
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="120">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateHandle(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="edit.textMap[edit.status]" :visible.sync="edit.visible">
      <el-form ref="dataForm" :rules="edit.rules" :model="edit.temp" label-position="left" label-width="80px" style="margin-left:20px;">
        <el-form-item label="用例编号" prop="case_num">
          <el-input v-model="edit.temp.case_num" />
        </el-form-item>
        <el-form-item label="用例名称" prop="case_title">
          <el-input v-model="edit.temp.case_title" />
        </el-form-item>
        <el-form-item label="用例类型" prop="case_type">
          <el-select v-model="edit.temp.case_type" class="filter-item" placeholder="请选择">
            <el-option value="">-- 请选择 -- </el-option>
            <el-option v-for="item in caseType" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="edit.temp.mark" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" placeholder="输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit.visible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateOrAddData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择需要变更到的目录"
      :visible.sync="chooseFolder.visible"
      width="28%"
      :close-on-click-modal="false"
      :center="true"
    >
      <el-cascader
        v-model="chooseFolder.value"
        placeholder="请输入搜索关键字"
        :options="chooseFolder.options"
        :props="{ expandTrigger: 'hover', value: 'id', label: 'classify_name', checkStrictly: true}"
        style="width:300px;"
        filterable
      />
      <el-button type="primary" @click="saveChangeFolder">确定</el-button>
      <el-button @click="chooseFolder.visible=false">取消</el-button>
    </el-dialog>

    <el-dialog
      title="请选择需要添加的测试集"
      :visible.sync="caseSetFolder.visible"
      width="45%"
      :close-on-click-modal="false"
      :center="true"
      :close="handleCaseSetClose"
    >
      <div class="caset_container">
        <div class="caseset_mian">
          <label class="caseset_lable">请选择测试集（可选多个）：</label>
          <el-select v-model="casetSetItem" filterable multiple size="medium" style="width: 65%" placeholder="可搜索测试集">
            <el-option
              v-for="item in casetSetOptions"
              :key="item.id"
              :label="item.set_name"
              :value="item.id"
            />
          </el-select>
          <el-button size="medium" class="el-icon-plus" @click="addaseSet">测试集</el-button>
        </div>
        <div class="caseset_footer">
          <el-button type="primary" size="medium" @click="batchHancleCastSet">确定</el-button>
          <el-button size="medium" @click="handleCaseSetClose">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <CaseSetDialog
      v-if="showDialog"
      :case-set-item="caseSetItem"
      @closeDialog="closeDialog"
    />
  </div>
</template>

<script>
import { listCaseCategory, caseList, caseEdit, caseDel, changeCaseClass } from '@/api/caseStep'
import { listCaseSet, addCase2Set } from '@/api/caseSet'
import mixinBaseView from '@/mixins/view-base.js'
import { parseTreeData } from '@/utils/commonUtil'
import CaseSetDialog from '../../caseSet/component/CaseSetDialog.vue'

export default {
  components: {
    CaseSetDialog
  },
  mixins: [mixinBaseView],
  props: {
    classifyNode: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      commonPageSetting: {
        entityTitle: '测试用例',
        entityNameKey: 'case_title',
        entityIdKey: 'id',
        listApi: caseList,
        editApi: caseEdit,
        delApi: caseDel,
        beforeSendEdit(vm) {
          if (vm.classifyNode === undefined) {
            vm.$message.error('当前节点不能添加测试用例')
            return false
          }
          return true
        },
        resetTemp(vm) {
          vm.edit.temp.classify_id = vm.classifyNode === undefined ? '' : vm.classifyNode.id
        }
      },
      addFlag: false,
      nodeLevel: 1,
      listQuery: { // 查询条件
        caseName: '',
        caseType: ''
      },
      // 编辑/新增表单
      edit: {
        textMap: {
          update: '编辑测试用例',
          create: '新增测试用例'
        },
        temp: {
          id: undefined,
          case_num: '',
          case_title: '',
          case_type: '',
          mark: '',
          classify_id: this.classifyNode === undefined ? '' : this.classifyNode.id
        },
        rules: {
          case_title: [{ required: true, message: '请输入用例名称', trigger: 'change' }],
          case_num: [{ required: true, message: '请选择用例编号', trigger: 'change' }]
        }
      },
      chooseFolder: {
        visible: false,
        value: undefined,
        options: []
      },
      caseSetFolder: {
        visible: false,
        value: undefined,
        options: []
      },
      casetSetItem: [],
      casetSetOptions: [],
      showDialog: false,
      caseSetItem: {
        id: undefined,
        set_name: '',
        mark: '',
        status: ''
      }
    }
  },
  computed: {
    caseType() {
      return this.$store.state.user.dictConfig.caseType
    },
    listParams() {
      const params = {}
      if (this.classifyNode === undefined || this.classifyNode.classify_level === 0) {
        params.c = 'allCase'
      } else {
        params.classify_id = this.classifyNode.id
      }
      return params
    }
  },
  watch: {
    'classifyNode.id': function() {
      if (this.classifyNode.classify_level !== 1) {
        this.addFlag = false
      } else {
        this.addFlag = true
      }
      this.getData()
    },
    '$route'() {
      // 此处写router变化时，想要初始化或者是执行的方法......
      this.getData()
    }

  },
  methods: {
    // 过滤
    selfHandleFilter(data) {
      if (this.listQuery.caseName !== '') {
        data = data.filter(item => item.case_title.indexOf(this.listQuery.caseName) !== -1 || item.case_num.indexOf(this.listQuery.caseName) !== -1)
      }
      if (this.listQuery.caseType !== '') {
        data = data.filter(item => item.case_type === this.listQuery.caseType)
      }
      return data
    },
    // 批量操作
    batchHandle(command) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      if (command === 'changeFolder') {
        this.chooseFolder.value = undefined
        this.chooseFolder.visible = true
        const thisClassifyId = this.classifyNode !== undefined ? this.classifyNode.id : undefined
        listCaseCategory().then(response => {
          const data = response.data
          this.chooseFolder.options = parseTreeData(data.filter(item => item.classify_level === 0), data
            , (item, node) => item.parent_classify_id === node.id, item => {
              if (item.id === thisClassifyId) {
                item.disabled = true
              }
            }, true)
        })
      }
      if (command === 'batchDel') {
        this.batchDel()
      }
      if (command === 'addSuite') {
        // 清空选择项
        this.getCaseSet()
      }
    },
    // 变更到的目录节点
    saveChangeFolder() {
      if (!(this.chooseFolder.value instanceof Array)) {
        this.$message.warning('请先选择需要变更到的目录节点!')
        return
      }
      changeCaseClass(this.chooseFolder.value.pop(), this.selectIds).then(response => {
        this.chooseFolder.visible = false
        this.getData()
        this.$message.success('变更目录成功')
      })
    },
    getCaseSet() {
      const params = {}
      listCaseSet(params).then(response => {
        this.casetSetOptions = response.data
        this.caseSetFolder.visible = true
      })
    },
    handleCaseSetClose() {
      this.caseSetFolder.visible = false
      this.casetSetItem = []
    },
    batchHancleCastSet() {
      if (this.casetSetItem.length === 0) {
        this.$message.warning('请先选择至少一个测试集!')
        return
      }
      const self = this
      this.casetSetItem.forEach(function(setId) {
        self.selectIds.forEach(function(val) {
          const data = [val]
          self.addCase2SetHandle(data, setId)
        })
      })
      this.caseSetFolder.visible = false
      this.casetSetItem = []
      self.$notify({
        title: '通知',
        message: '批量添加到测试集成功',
        type: 'success',
        duration: 1800
      })
    },
    addCase2SetHandle(data, setId) {
      addCase2Set(data, setId).then(response => {
      }).catch(() => {
      })
    },
    addaseSet() {
      this.caseSetItem = {
        id: undefined,
        set_name: '',
        mark: '',
        status: 'create'
      }
      this.showDialog = true
    },
    // 关闭组名edit操作
    closeDialog(flag) {
      if (flag) {
        // 重新刷新表格内容
        this.getCaseSet()
      }
      this.showDialog = false
    }
  }
}
</script>

<style scoped>
  .el-dropdown {
    vertical-align: top;
  }
  .step-count {
    cursor: pointer;
  }
  .step-count:hover {
    background-color: #fdf6ec;
    border-color: #faecd8;
    color: #e6a23c;
  }

  /*.el-input,.el-textarea{*/
  /*  width: 65%;*/
  /*}*/

  .caset_container::before,
  .caset_container::after{
    display: table;
    clear: both;
  }
  .caseset_mian {
    margin: 10px 0px;
  }
  .caseset_lable{
    margin: 17px;
  }

  .caseset_footer::before,
  .caseset_footer::after{
    content: '';
    display: table;
    clear: right;
  }
  .caseset_footer button{
    float: right;
    margin: 0 10px;
  }
</style>
